import { defineStore } from 'pinia'
import { getProducts, createProduct, updateProduct, deleteProduct } from '@/api/product'
import { ElMessage } from 'element-plus'

export const useProductStore = defineStore('product', {
  state: () => ({
    products: [],
    total: 0
  }),

  actions: {
    // 获取商品列表
    async getProducts(params) {
      try {
        console.log('开始获取商品列表，参数:', params)
        const res = await getProducts(params)
        console.log('商品列表响应:', res)

        if (res.code === 200) {
          // 处理不同的响应格式
          if (Array.isArray(res.data)) {
            this.products = res.data
            this.total = res.data.length
          } else if (res.data && res.data.records) {
            this.products = res.data.records
            this.total = res.data.total
          } else if (res.data) {
            this.products = [res.data]
            this.total = 1
          } else {
            this.products = []
            this.total = 0
          }
          return res.data
        }
        throw new Error(res.message || '获取商品列表失败')
      } catch (error) {
        console.error('获取商品列表失败:', error)
        ElMessage.error(error.message || '获取商品列表失败')
        this.products = []
        this.total = 0
        throw error
      }
    },

    // 创建商品
    async createProduct(data) {
      try {
        console.log('创建商品，数据:', data)
        const res = await createProduct(data)
        if (res.code === 200) {
          ElMessage.success('创建商品成功')
          await this.getProducts()
          return res.data
        }
        throw new Error(res.message || '创建商品失败')
      } catch (error) {
        console.error('创建商品失败:', error)
        ElMessage.error(error.message || '创建商品失败')
        throw error
      }
    },

    // 更新商品
    async updateProduct(data) {
      try {
        console.log('更新商品，数据:', data)
        const res = await updateProduct(data)
        if (res.code === 200) {
          ElMessage.success('更新商品成功')
          await this.getProducts()
          return res.data
        }
        throw new Error(res.message || '更新商品失败')
      } catch (error) {
        console.error('更新商品失败:', error)
        ElMessage.error(error.message || '更新商品失败')
        throw error
      }
    },

    // 删除商品
    async deleteProduct(id) {
      try {
        console.log('删除商品，ID:', id)
        const res = await deleteProduct(id)
        if (res.code === 200) {
          ElMessage.success('删除商品成功')
          await this.getProducts()
          return res.data
        }
        throw new Error(res.message || '删除商品失败')
      } catch (error) {
        console.error('删除商品失败:', error)
        ElMessage.error(error.message || '删除商品失败')
        throw error
      }
    }
  }
}) 